from langchain.chat_models import init_chat_model
from langchain_core.messages import HumanMessage
from langchain_core.tools import tool
from duckduckgo_search import DDGS

@tool
def add(a: int, b: int) -> int:
    """Adds a and b."""
    return a + b

@tool
def get_web_data(query:str) -> str:
  """使用DuckDuckGo搜索引擎进行搜索"""

  results = DDGS().text(query, max_results=10)

  return results

tools = [add,get_web_data]

api_key = "sk-pdfifkpjdlxvyvgkerbluaotktpznsmpbcvskjauotenxgvz"
base_url = "https://api.siliconflow.cn/v1"
model = init_chat_model("Qwen/Qwen2.5-72B-Instruct", model_provider="openai",api_key=api_key,base_url=base_url)

llm_with_tools = model.bind_tools(tools)

query = "介绍一下招联消费金融有限公司"

messages = [HumanMessage(query)]

ai_msg = llm_with_tools.invoke(messages)

print(ai_msg.tool_calls)

messages.append(ai_msg)

for tool_call in ai_msg.tool_calls:
    selected_tool = {"add": add,"get_web_data":get_web_data}[tool_call["name"].lower()]
    tool_msg = selected_tool.invoke(tool_call)
    print(tool_msg)
    messages.append(tool_msg)

print("==============================")
print(llm_with_tools.invoke(messages).content)